package com.template.utlis;

import com.template.entity.User;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.List;


/**
 * @author wangqi
 * @date 2024-01-08 11:08
 */
public class FeiShuUtil {
    private static  final Logger log= LoggerFactory.getLogger(FeiShuUtil.class);
    public static final String  CODE="code";

    public static final String AT_ALL="<at user_id=\"all\">所有人</at>";

    public static final String AT_ONE="<at user_id=\"{0}\">{1}</at>";

    public static String GenSign(String secret, Long timestamp) {
        try {
            //把timestamp+"\n"+密钥当做签名字符串
            String stringToSign = timestamp + "\n" + secret;
            //使用HmacSHA256算法计算签名
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(new byte[]{});
            return new String(Base64.encodeBase64(signData));
        } catch (Exception e) {
            log.error("飞书生成机器人发言签名失败,{}", e.getStackTrace());
            return null;
        }
    }

    public static String buildAtTextContent(String content, List<User> idList, boolean atAll) {
        StringBuilder stringBuilder = new StringBuilder();
        if (idList != null && !idList.isEmpty()) {
            for (User user : idList) {
                if (user != null && !StringUtils.isEmpty(user.getId())) {
                    stringBuilder.append(String.format(AT_ONE, user.getId(), user.getName()));
                }
            }
        }
        if (atAll) {
            stringBuilder.append(AT_ALL);
        }
        stringBuilder.append(content);
        return stringBuilder.toString();
    }


}
